<?php

namespace App\Jobs\Stats\Platform\Settlement;

use App\Jobs\Stats\Stats as JobStats;
use App\Models\Admin\Stats\Platform\Settlement\Month as Stats;
use App\Models\Admin\Stats\Platform\Settlement\Day as StatsDay;
use Helper\Timed;
use Illuminate\Support\Str;

class Month extends JobStats
{

    /**
     * 执行统计任务。
     *
     * @return void
     */
    public function stats()
    {
        $columns[] = 'currency';
        $columns[] = 'SUM(bet_num) as bet_num';
        $columns[] = 'SUM(amount) as amount';
        $columns[] = 'SUM(revenue) as revenue';
        $columns[] = 'GROUP_CONCAT(DISTINCT rate SEPARATOR "|") AS rate';
        $columns[] = "CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})) AS usd_bet_num";
        $columns[] = "CAST(SUM(usd->'$.amount') AS DECIMAL({$this->decimals()},{$this->precision()})) AS usd_amount";
        $columns[] = "CAST(SUM(usd->'$.revenue') AS DECIMAL({$this->decimals()},{$this->precision()})) AS usd_revenue";

        $stats = StatsDay::dbTable()->selectRaw(implode(',', $columns))
            ->where('timed', '<', Timed::getMonthNextTimed($this->task->timed))
            ->where('timed', '>=', $this->task->timed)
            ->where('plat_code', $this->task->plat_code)
            ->groupBy('currency')
            ->get();

        $stats->each(function ($item) {
            Stats::updateOrCreate(
                $this->task->only(['timed', 'plat_code']) + ['currency' => $item['currency']],
                [
                    'rates' => Str::of($item['rate'])->explode('|')->transform(function ($rate) {
                        return $this->makeRound($rate);
                    }),
                    'bet_num' => $item['bet_num'],
                    'amount' => $item['amount'],
                    'revenue' => $item['revenue'],
                    'usd' => [
                        'bet_num' => $this->makeRound($item['usd_bet_num']),
                        'amount' => $this->makeRound($item['usd_amount']),
                        'revenue' => $this->makeRound($item['usd_revenue']),
                    ]
                ]
            );
        });
    }
}
